package com.esd.device.controller;

import com.esd.common.pojo.R;
import com.esd.device.entity.vo.DeviceVo;
import com.esd.device.service.DeviceService;
import com.esd.device.utils.NumberUtils;
import com.esd.device.utils.Tcp_Utils_Nio;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 查询离子风机的一些信息，主要是每种终端的返回都不一样
 * 所以单独为每种终端做不同的实现
 */
@Slf4j
@RestController
@RequestMapping("fan/search")
public class FanSearchController extends BaseOperationController {
    @Autowired
    private Tcp_Utils_Nio tcp_utils;
    @Autowired
    private DeviceService deviceService ;

    // 轮询指令，获取终端状态
    @PostMapping("getDetail")
    public R getDetailForDevice(
            @RequestBody DeviceVo deviceVo
    ) {
        R r = sendCommandForSearch(deviceVo, "03 05 01" , tcp_utils) ;
        if (r.getCode() == 500) {
            return  r;
        } else{
            if (deviceVo.getDeviceTypeName().equals("旧版离子风扇")) {
                String resultStr = r.getMsg().substring(15, 29);
                // 先取前两位 获取终端状态
                String statusStr = resultStr.substring(0, 2);
                // 通信协议规定的，前两位保存终端状态，需要转化为二进制才能分析
                statusStr = NumberUtils.hexToBinary(statusStr, 8);
                // 风档
                Integer windLevel = NumberUtils.binaryToInt(statusStr.substring(0, 3));
                // 封窗
                String windowOpen = statusStr.charAt(3) == '0' ? "闭合" : "打开";
                // 清扫状态
                String cleanStatus = statusStr.charAt(4) == '0' ? "未清扫" : "清扫";
                // 高压报警状态
                String highStatus = statusStr.charAt(5) == '0' ? "未报警" : "报警";
                // 风扇报警状态
                String fanStatus = statusStr.charAt(6) == '0' ? "未报警" : "报警";
                // 开关机
                String powerStatus = statusStr.charAt(7) == '0' ? "关机" : "开机";
                // 放电针电压
                Integer fdzdy = NumberUtils.hexToInt(resultStr.substring(3, 5));
                // 平衡电压
                Integer phdy = NumberUtils.hexToInt(resultStr.substring(6, 8));
                // 保养后已工作 小时
                int workTimeHours = NumberUtils.hexToInt(resultStr.substring(9, 14).replace(" ", ""));
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("stationId", deviceVo.getStationId());
                dataMap.put("deviceTypeName", deviceVo.getDeviceTypeName());
                dataMap.put("windLevel", windLevel); // 风档
                dataMap.put("windowOpen", windowOpen); // 封窗
                dataMap.put("cleanStatus", cleanStatus); // 清扫状态
                dataMap.put("highStatus", highStatus); // 高压报警状态
                dataMap.put("fanStatus", fanStatus); // 风扇报警状态
                dataMap.put("powerStatus", powerStatus); // 开关机
                dataMap.put("fdzdy", fdzdy); // 放电针电压
                dataMap.put("phdy", phdy); // 平衡电压
                dataMap.put("workTime", workTimeHours); // 保养后工作小时
                dataMap.put("message", "查询离子风扇信息成功！！");
                return R.ok(dataMap);
            }else {
                String resultStr = r.getMsg().substring(15, 71);
                // 先取前两位 获取终端状态
                String [] ss = resultStr.split(" ");
                String statusStr = ss[0];
                // 通信协议规定的，前两位保存终端状态，需要转化为二进制才能分析
                statusStr = NumberUtils.hexToBinary(statusStr, 8);
                Map<String , Object> dataMap = new HashMap<>();
                // 风档
                Integer windLevel = NumberUtils.binaryToInt(statusStr.substring(0, 3)) ;
                dataMap.put("windLevel", windLevel);
                // 报警
                String fanStatus = (statusStr.charAt(3)=='0' ? "未报警" : "报警");
                dataMap.put("fanStatus", fanStatus);
                // 清扫状态
                String cleanStatus = statusStr.charAt(6)=='0'? "未清扫" : "正在清扫";
                dataMap.put("cleanStatus", cleanStatus);
                // 开关机
                String powerStatus = statusStr.charAt(7)=='0'? "关机" : "开机";
                dataMap.put("powerStatus", powerStatus);
                // 获取通道数量
                int channelCount = deviceService.countChannels(deviceVo.getDeviceId());
                // 风扇状态
                String fanStatusStr = ss[1] ;
                fanStatusStr = NumberUtils.hexToBinary(fanStatusStr, 8);
                // 高压报警状态
                String highStatusStr = ss[2];
                highStatusStr = NumberUtils.hexToBinary(highStatusStr, 8);
                // 封窗报警状态
                String openWindowStatusStr = ss[3];
                openWindowStatusStr = NumberUtils.hexToBinary(openWindowStatusStr, 8);
                // 清扫报警状态
                String cleanStatusStr = ss[4];
                cleanStatusStr = NumberUtils.hexToBinary(cleanStatusStr, 8);
                StringBuilder fanStatusList = new StringBuilder();
                StringBuilder highStatusList = new StringBuilder();
                StringBuilder openWindowStatusList = new StringBuilder();
                StringBuilder cleaStatusList = new StringBuilder();
                StringBuilder powerList = new StringBuilder();
                StringBuilder balancePowerList = new StringBuilder();
                // 解析通道数据
                for (int i = 1; i <= channelCount; i++) {
                    if (i !=1){
                        fanStatusList.append(",");
                        highStatusList.append(",");
                        openWindowStatusList.append(",");
                        cleaStatusList.append(",");
                        powerList.append(",");
                        balancePowerList.append(",");
                    }

                    fanStatusList.append(fanStatusStr.charAt(fanStatusStr.length() - i) == '0' ? "正常" : "异常");
                    highStatusList.append(highStatusStr.charAt(highStatusStr.length() - i) == '0' ? "正常" : "异常");
                    openWindowStatusList.append(openWindowStatusStr.charAt(openWindowStatusStr.length() - i) == '1' ? "正常" : "异常");
                    cleaStatusList.append(cleanStatusStr.charAt(cleanStatusStr.length() - i) == '0' ? "正常" : "异常");
                    powerList.append(NumberUtils.hexToInt(ss[4 + i]) * 100).append("V");
                    balancePowerList.append(NumberUtils.hexToInt(ss[10 + i])).append("V");
                }
                int hasWorkTime = NumberUtils.hexToInt(ss[ss.length - 2] + ss[ss.length - 1]);
                dataMap.put("hasWorkTime",hasWorkTime); // 已工作时间
                dataMap.put("fanStatusList", fanStatusList.toString());
                dataMap.put("highStatusList", highStatusList.toString());
                dataMap.put("openWindowStatusList", openWindowStatusList.toString());
                dataMap.put("cleaStatusList", cleaStatusList.toString());
                dataMap.put("powerList", powerList.toString());
                dataMap.put("balancePowerList", balancePowerList.toString()); // 平衡电压
                dataMap.put("message", "查询离子风扇信息成功！！");
                return R.ok(dataMap);
            }
        }
    }
    // 查询自动启动时间
    @PostMapping("getStartTime/{timeStr}")
    public R getStartTime(
            @RequestBody DeviceVo deviceVo ,
            @PathVariable String timeStr
    ) {
        R r1 = sendCommandForSearch(deviceVo, "03 03 " + timeStr , tcp_utils) ;
        Map<String, Object> result = new HashMap<>();
        String resultStr1 = r1.getMsg();
        if (r1.getCode() == 500) {
            if(resultStr1.equals("error")) {
                return  R.error("可能网关停机了，请检查！！");
            }
            if(resultStr1.isEmpty()) {
                return  R.error("无返回数据，终端是否正常运行！！");
            }
            return  R.error("查询终端" + deviceVo.getStationId() + "自启动时间失败！！");
        }else{
            resultStr1 = getTimeResult(resultStr1);
            String timeStr1 = setTime(resultStr1);
            
            result.put("message", "获取自启动时间成功，时间为: "
                    + timeStr1);
            result.put("timeStr", timeStr1);
            return R.ok(result);
        }
    }

    // 查询休眠时间
    @PostMapping("getSleepTime/{val}")
    public R getSleepTime(
            @RequestBody DeviceVo deviceVo ,
            @PathVariable String val
    ) {
        R r1 = sendCommandForSearch(deviceVo, "03 03 " + val , tcp_utils) ;
        Map<String, Object> result = new HashMap<>();
        String resultStr1 = r1.getMsg();
        if (r1.getCode() == 500) {
            if(resultStr1.equals("error")) {
                return  R.error("可能网关停机了，请检查！！");
            }
            if(resultStr1.isEmpty()) {
                return  R.error("无返回数据，终端是否正常运行！！");
            }
            return  R.error("查询终端" + deviceVo.getStationId() + "休眠时间失败！！");
        } else {
            resultStr1 = getTimeResult(resultStr1);
            String timeStr1 = setTime(resultStr1);
            result.put("message", "获取休眠时间成功，时间为: "+ timeStr1);
            result.put("timeStr", timeStr1);
            return R.ok(result);
        }
    }
    
    // 查询清扫时间
    @PostMapping("getCleanTime")
    public R getCleanTime(@RequestBody DeviceVo deviceVo) {
        R r = sendCommandForSearch(deviceVo, "03 03 08" , tcp_utils) ;
        Map<String, Object> result = new HashMap<>();
        if (r.getCode() == 500) {
            return r;
        } else {
            String resultStr = r.getMsg();
            resultStr = getTimeResult(resultStr);
            String timeStr = setTime(resultStr);
            result.put("message", "获取自动清扫时间成功，时间为: " + timeStr);
            result.put("timeStr", timeStr);
            return R.ok(result);
        }
    }

    // 查询平衡电压上下限
    @PostMapping("getVoltageLimit")
    public R getVoltageLimit(@RequestBody DeviceVo deviceVo) {
        R r = sendCommandForSearch(deviceVo, "03 03 0A" , tcp_utils) ;
        Map<String, Object> result = new HashMap<>();
        if (r.getCode() == 500) {
            return r;
        } else {
            String resultStr = r.getMsg();
            String[] ss = resultStr.substring(18,23).split(" ");
            int max = 0;
            int min = 0;
            if (ss.length == 2) {
                max = NumberUtils.hexToInt(ss[0]);
                min = NumberUtils.hexToInt(ss[1]);
            }
            result.put("message", "获取平衡电压上下限成功，为: " + min + "-" + max + " v");
            result.put("max", max);
            result.put("min", min);
            return R.ok(result);
        }
    }

    // 查询最长保养时间
    @PostMapping("getMaintainTime")
    public R getMaintainTime(
            @RequestBody DeviceVo deviceVo
    ) {
        R r = sendCommandForSearch(deviceVo, "03 03 0D" , tcp_utils) ;
        Map<String, Object> result = new HashMap<>();
        if (r.getCode() == 500) {
            return r;
        } else {
            String resultStr = r.getMsg();
            String ss = resultStr.substring(18,23).replace(" ", "").trim();
            int hours = NumberUtils.hexToInt(ss);
            result.put("message", "获取最长保养时间成功，时间为: " + hours + " 小时。");
            result.put("hours", hours);
            return R.ok(result);
        }
    }

    // 查询放电针上下限
    @PostMapping("getPowerLimit")
    public R getPowerLimit(@RequestBody DeviceVo deviceVo) {
        R r = sendCommandForSearch(deviceVo, "03 03 0F" , tcp_utils) ;
        Map<String, Object> result = new HashMap<>();
        if (r.getCode() == 500) {
            return r;
        } else {
            String resultStr = r.getMsg();
            String[] ss = resultStr.substring(18,23).split(" ");
            int max = 0;
            int min = 0;
            if (ss.length == 2) {
                max = NumberUtils.hexToInt(ss[0]);
                min = NumberUtils.hexToInt(ss[1]);
            }
            result.put("message", "获取放电针电压上下限成功，为: " + min + "-" + max + " v");
            result.put("max", max);
            result.put("min", min);
            return R.ok(result);
        }
    }

}
